package com.exer2;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName PaymentFactory
 * @Description 容器工厂
 * @Author Kx
 * @Date 2025/4/16 20:04
 * @Version 1.0
 */
public class PaymentFactory {
    private final Map<String,Object> map = new HashMap<>();

    public PaymentFactory(String pay,double money) {
        Scan.init(map);

        PaymentService handle = handle(pay);

        handle.pay(money);
    }

    /***
     * @author: kx
     * @date: 2025/4/16 20:56
     * @param pay : 支付方式
     * @description: 自动注入属性
    */
    private PaymentService handle(String pay) {
        PaymentService paymentService = new PaymentService();

        for (Field field : PaymentService.class.getDeclaredFields()) {
            // 判断属性是否被注解标注
            if (field.isAnnotationPresent(Inject.class)) {
                // 判断是否可读
                if (!field.canAccess(paymentService)) {
                    field.setAccessible(true);
                }
                try {
                    // 根据不同的支付方式，注入不同的支付对象
                    switch (pay) {
                        case "微信":
                            field.set(paymentService, new WeChatPayment());
                            break;
                        case "支付宝":
                            field.set(paymentService, new AlipayPayment());
                            break;
                        case "信用卡":
                            field.set(paymentService, new CreditCardPayment());
                            break;
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return paymentService;
    }
}
